# -*- coding: utf-8 -*-
"""An example of a conversation with a ReAct agent."""
import io
import os
import sys

import agentscope
from agentscope.agents import UserAgent
from agentscope.agents.react_agent import ReActAgent
from agentscope.agents.dialog_agent import DialogAgent
from agentscope.message.msg import Msg
from agentscope.service import (
    ServiceToolkit,
    ServiceResponse,
    ServiceExecStatus,
)

model_configs = [
    {
        "model_type": "openai_chat",
        "config_name": "vllm-openai-api",
        "model_name": "Qwen/Qwen2.5-7B-Instruct",
        "client_args": {
            "base_url": "https://api-inference.modelscope.cn/v1",
        },
        "api_key": os.environ.get("MODELSCOPE_ACCESS_TOKEN"),
        "generate_args": {"temperature": 0.2},
        "stream": True,
    },
    {
        "model_type": "openai_chat",
        "config_name": "deepseek-r1:7b",
        "model_name": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
        "client_args": {
            "base_url": "https://api.siliconflow.cn/v1",
        },
        "api_key": os.environ.get("SILICON_API_KEY"),
        "generate_args": {"temperature": 0.6},
        "stream": True,
    }
]
agentscope.init(model_configs=model_configs)




# Prepare a new tool function
def execute_python_code(code: str) -> ServiceResponse:  # pylint: disable=C0301
    """
    执行python代码，并且返回最终结果。请注意为了正确的返回结果，传入的代码必须在最后显式的调用print将结果打印出来！
    Args:
        code (`str`):
            The Python code to be executed.
    """  # noqa

    # Create a StringIO object to capture the output
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout

    try:
        # Using `exec` to execute code
        exec(code)
    except Exception as e:
        # If an exception occurs, capture the exception information
        output = str(e)
        status = ServiceExecStatus.ERROR
    else:
        # If the execution is successful, capture the output
        output = new_stdout.getvalue()
        status = ServiceExecStatus.SUCCESS
    finally:
        # Recover the standard output
        sys.stdout = old_stdout

    # Wrap the output and status into a ServiceResponse object
    return ServiceResponse(status, output)


# Prepare the tools for the agent
service_toolkit = ServiceToolkit()

service_toolkit.add(execute_python_code)
# service_toolkit.add(deep_thinking)

# Create agents
agent = ReActAgent(
    name="assistant",
    model_config_name="vllm-openai-api",
    verbose=True,
    service_toolkit=service_toolkit,
    max_iters=3,
)
user = UserAgent(name="User", input_hint="User Input ('exit' to quit): ")

# Build
x = None
while True:
    x = user(x)
    if x.content == "exit":
        break
    x = agent(x)
